<?php

/**
 * Make use of js/css jQuery Mobile datebox plugin (https://github.com/jtsage/jquery-mobile-datebox)
 *
 * @package    symfony
 * @subpackage widget
 * @author     Jonas Fischer <info@jonasfischer.net>
 */
class jfPDWidgetFormDate extends sfWidgetFormInputText
{
	
	protected $jfPDDefaultAttibutes = array(
		/*'type' => 'date',*/
		'data-role' => 'datebox',
		'data-options' => array('mode' => 'calbox'),
	);
	
  public function __construct($options = array(), $attributes = array())
  {
    $attributes = array_merge_recursive($this->jfPDDefaultAttibutes, $attributes);
    parent::__construct($options, $attributes);
  }

  protected function configure($options = array(), $attributes = array())
  {
    $this->addOption('format', 'Y-m-d');
    return parent::configure($options, $attributes);
  }

  /**
   * @param  string $name        The element name
   * @param  string $value       The value displayed in this widget
   * @param  array  $attributes  An array of HTML attributes to be merged with the default HTML attributes
   * @param  array  $errors      An array of errors for the field
   *
   * @return string An HTML tag string
   *
   * @see sfWidgetForm
   */
  public function render($name, $value = null, $attributes = array(), $errors = array())
  {
  	if (is_array($attributes['data-options'])) {
  		$attributes['data-options'] = json_encode($attributes['data-options']);
  	}
    $response = sfContext::getInstance()->getResponse();
    $response->addStylesheet('/jfPortableDeviceExtFormsPlugin/datebox/jquery.mobile.datebox.css', 'last');
    $response->addJavascript('/jfPortableDeviceExtFormsPlugin/datebox/jquery.mobile.datebox.min.js', 'last');
    
    $date = strtotime($value);
    if ($date) {
    	$value = date($this->getOption('format'), $date);
    }
    
    return parent::render($name, $value, $attributes, $errors);
  }
}
